//
//  HGRequest.m
//  HGMM
//
//  Created by 2008-bj5 on 15/8/8.
//  Copyright (c) 2015年 cc. All rights reserved.
//

#import "HGRequest.h"
//#import "HGRequestUtil.h"
#import "NSString+URL.h"
#import <AFNetworking/AFNetworking.h>
#import "Param.h"
#import "LinkServers.h"

@implementation HGRequest

- (void)GET:(CDVInvokedUrlCommand*)command{
    
    if ([command.arguments count] != 4 ||
        ![[command.arguments objectAtIndex:0] isKindOfClass:[NSString class]] ||
        ![[command.arguments objectAtIndex:1] isKindOfClass:[NSString class]] ||
        ![[command.arguments objectAtIndex:2] isKindOfClass:[NSArray class]]  ) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    NSString *server = [command.arguments objectAtIndex:0];
    NSString *url = [command.arguments objectAtIndex:1];
    NSArray *arr = [command.arguments objectAtIndex:2];
    
    NSArray *params = [self toParams:arr];
    
    if (!params) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    NSString *urlParam = @"";
    for (Param *p in params) {
        if (p.isFile) {
            continue ;
        }
        if ([p.value isKindOfClass:[NSString class]]) {
            urlParam = [urlParam stringByAppendingFormat:@"%@%@=%@", urlParam.length>0?@"&":@"", p.key, [p.value URLEncodedString]];
        } else {
            urlParam = [urlParam stringByAppendingFormat:@"%@%@=%@", urlParam.length>0?@"&":@"", p.key, p.value];
        }
        
    }
    
    url = [url stringByAppendingFormat:@"?%@", urlParam];
   
    
    NSString *host = [LinkServers shareInstance].linkhost;
    NSString *allUrl = [NSString stringWithFormat:@"http://%@:8181/HGMIDE/hgmeam?http.protocol.content-charset=UTF-8",host];
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.requestSerializer  = [AFHTTPRequestSerializer serializer];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置请求头
    [sessionManager.requestSerializer setValue:server forHTTPHeaderField:@"hgmeam_header_server"];
   
    [sessionManager.requestSerializer setValue:url forHTTPHeaderField:@"hgmeam_header_url"];
    
    
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/html", @"application/json", @"text/xml", nil];

   
    
    
    NSURLSessionDataTask *task = [sessionManager GET:allUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
       // success(sessionManager,responseObject);
        
        CDVPluginResult* pluginResult = nil;
        
        NSString * reString  =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        if ([[command.arguments objectAtIndex:3] boolValue]) {
            NSString *tmp = nil; //manager.responseString;
            NSError *error = nil;
            
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
            
            if (error) {
                CCLog(@"get error: %@, %@", tmp, error);
                CDVPluginResult* pluginResult = nil;
                
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:reString];
                
                [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                return ;
            }
            if ([json isKindOfClass:[NSDictionary class]]) {
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:json];
            } else if ([json isKindOfClass:[NSArray class]]) {
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:json];
            } else {
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:reString];
            }
        } else {
            
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:reString];
        }
        
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
       
        CDVPluginResult* pluginResult = nil;
        

        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"服务请求出错"];
        
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
        
    }];
    
    [task resume];
    

    
}

- (void)POST:(CDVInvokedUrlCommand*)command{
    if ([command.arguments count] != 4 ||
        ![[command.arguments objectAtIndex:0] isKindOfClass:[NSString class]] ||
        ![[command.arguments objectAtIndex:1] isKindOfClass:[NSString class]] ||
        ![[command.arguments objectAtIndex:2] isKindOfClass:[NSArray class]]  ) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    
   
    
    NSString *server = [command.arguments objectAtIndex:0];
    NSString *url = [command.arguments objectAtIndex:1];
    NSArray *arr = [command.arguments objectAtIndex:2];
    
    NSArray *params = [self toParams:arr];
    
    if (!params) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    NSString *error = @"";
    BOOL hasFile = NO;
    
    NSFileManager *fm = [NSFileManager defaultManager];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSMutableDictionary *fps = [NSMutableDictionary dictionary];
    
    for (Param *p in params) {
        if (!p.isFile) {
            [parameters setObject:p.value forKey:p.key];
            continue ;
        }
        hasFile = YES;
        [fps setObject:p.value forKey:p.key];
        
        if (![fm fileExistsAtPath:p.fileName]) {
            error = [error stringByAppendingFormat:@"%@%@", error.length>0?@", ":@"", p.value];
        }
    }
    
    if ([error length] > 0) {
        error = [NSString stringWithFormat:@"文件不存在：%@", error];
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    NSString *host = [LinkServers shareInstance].linkhost;
    NSString *allUrl = [NSString stringWithFormat:@"http://%@:8181/HGMIDE/hgmeam?http.protocol.content-charset=UTF-8",host];
    
    if (hasFile) {
        
       
      
        
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = 20;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
        manager.requestSerializer  = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
      
        //设置请求头
        [manager.requestSerializer setValue:server forHTTPHeaderField:@"hgmeam_header_server"];
        [manager.requestSerializer setValue:url forHTTPHeaderField:@"hgmeam_header_url"];
        
        
        NSURLSessionDataTask *task = [manager POST:allUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            for (NSString *f in fps) {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:fps[f]] name:f error:nil];
            }
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            CDVPluginResult* pluginResult = nil;
            NSString * reString  =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            
            if ([[command.arguments objectAtIndex:3] boolValue]) {
                NSString *tmp = nil; //operation.responseString;
                NSError *error = nil;
                
                id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
                
                if (error) {
                    CCLog(@"post error: %@, %@", tmp, error);
                    CDVPluginResult* pluginResult = nil;
                    
                    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:reString];
                    
                    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                    return ;
                }
                if ([json isKindOfClass:[NSDictionary class]]) {
                    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:json];
                } else if ([json isKindOfClass:[NSArray class]]) {
                    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:json];
                } else {
                    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:reString];
                }
            } else {
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:reString];
            }
            
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
          
            CDVPluginResult* pluginResult = nil;
            
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"服务请求出错"];
            
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            
        }];
        
        [task resume];
        
    } else {
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer  = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST"]];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/html", @"application/json", @"text/xml", nil];
        
        //设置请求头
        [manager.requestSerializer setValue:server forHTTPHeaderField:@"hgmeam_header_server"];
        [manager.requestSerializer setValue:url forHTTPHeaderField:@"hgmeam_header_url"];
        
        
        NSURLSessionDataTask *task = [manager POST:allUrl parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            CDVPluginResult* pluginResult = nil;
            
            NSString * reString  =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            
            if ([[command.arguments objectAtIndex:3] boolValue]) {
                NSString *tmp = nil;
                NSError *error = nil;
                
                id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
                
                if (error) {
                    CCLog(@"post error: %@, %@", tmp, error);
                    CDVPluginResult* pluginResult = nil;
                    
                    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:reString];
                    
                    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                    return ;
                }
                if ([json isKindOfClass:[NSDictionary class]]) {
                    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:json];
                } else if ([json isKindOfClass:[NSArray class]]) {
                    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:json];
                } else {
                    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:reString];
                }
            } else {
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:reString];
            }
            
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            CDVPluginResult* pluginResult = nil;
            
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"服务请求出错"];
            
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            
         
        }];
        
        [task resume];
        

    }
    
    
}



- (NSArray *)toParams:(NSArray *)param{
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    
    if (!param || param.count == 0) {
        return arr;
    }
    
    for (id p in param) {
        if (![p isKindOfClass:[NSDictionary class]]) {
            return nil;
        }
        Param *pa = [[Param alloc] init];
        NSDictionary *dic = p;
        
        NSString *type = [dic valueForKey:@"type"];
        if ([@"file" isEqualToString:type]) {
            pa.isFile = YES;
        } else {
            pa.isFile = NO;
        }
        
        for (NSString *key in dic) {
            if (pa.isFile && [@"type" isEqualToString:key]) {
                continue;
            }
            pa.key = key;
            pa.value = dic[key];
        }
        if (pa.isFile) {
            if ([pa.value hasPrefix:@"file://"]) {
                pa.fileName = [pa.value substringFromIndex:[@"file://" length]];
            } else {
                pa.fileName = pa.value;
            }
            
            CCLog(@"Param file: %@ = %@", pa.key, pa.fileName);
        }
        [arr addObject:pa];
    }
    
    return arr;
}


@end
